/*
	This file is part of SRServerLibrary.
	Foobar is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	SRServerLibrary is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with SRServerLibrary.  If not, see <http://www.gnu.org/licenses/>.
*/


#include "SRPluginLoader.h"
#include <QDebug>
#include <QDir>
#include "global.h"
#include <QLibrary>



SRPluginLoader::SRPluginLoader(SRSettings *s)
{
	settings = s;

	loadAllPlugins();
}


QList<SRPluginInterface*> SRPluginLoader::getPlugins()
{
	return loadedPlugins;
}

void SRPluginLoader::unloadPlugin(SRPluginInterface* p)
{
	int index = loadedPlugins.indexOf(p); // index of the plugin instance, and thus the index of it's plugin loader
	loadedPlugins.removeAt(index);
	loadedPluginsInterfaces.removeAt(index);
}


void SRPluginLoader::loadAllPlugins()
{
	qDebug() << __FILE__ << ": attempting to load plugins in " << settings->getPluginsPath();

	QDir pluginsDir(settings->getPluginsPath());

	foreach(QString dirName, pluginsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
	{
		qDebug() << "  looking for plugin in " << dirName;

		foreach(QString fileName, QDir(pluginsDir.absoluteFilePath(dirName)).entryList(SRSettings::validPluginNameFilter, QDir::Files))
		{
			QString fileAbsolutePath = QDir(pluginsDir.absoluteFilePath(dirName)).absoluteFilePath(fileName);
			if(QLibrary::isLibrary(fileAbsolutePath))
			{
				qDebug() << "    trying to load " << fileAbsolutePath;

				QPluginLoader *pluginLoader = new QPluginLoader(fileAbsolutePath);

				QObject *plugin = pluginLoader->instance();

				if(plugin)
				{
					SRPluginInterface *pluginInstance = qobject_cast<SRPluginInterface*>(plugin);

					if(pluginInstance)
					{
						// add plugin instance and pluginloader to list of loaded plugins
						loadedPlugins.append(pluginInstance);
						loadedPluginsInterfaces.append(pluginLoader);

						qDebug() << "      plugin successfully loaded";

						// initiate the plugin
						pluginInstance->initiate();
					}
					else qDebug() << pluginLoader->errorString();
				}
				else qDebug() << pluginLoader->errorString();
			}
			else
			{
				qDebug() << "    ignoring " << fileName << " (invalid suffix for current OS)";
			}
		}
	}
}
